package main

import (
	"flag"
	"net/http"

	"gitee.com/thubcc/rtlmmap/web"
	"github.com/gin-gonic/gin"
)

var (
	argReset = flag.Bool("r", false, "Reset PPM")
	argFc    = flag.String("f", "104.1e6", "LTE Center Freqency")
	argGain  = flag.String("g", "40.0", "Rx Gain")
	argSr    = flag.String("s", "1.92e6", "Rx Gain")
)
var (
	fmv  *web.FMView
	fafc func(float64)
)

func main() {
	flag.Parse()
	config := web.RFConfig{
		FreqCenter: web.Str1int(*argFc),
		SampleRate: web.Str1int(*argSr),
		Gain:       web.Str10int(*argGain),
	}
	r := gin.Default()
	ps := web.NewPorts(&config)
	r.GET("/plist", ps.List)
	r.GET("/open/:port", ps.PortSpecificationAPI("Open"))
	r.GET("/suspend/:port", ps.PortSpecificationAPI("Suspend"))
	r.GET("/start/:port", ps.PortSpecificationAPI("Start"))
	r.GET("/resume/:port", ps.PortSpecificationAPI("Resume"))
	r.GET("/fc/:port", ps.PortSpecificationAPI("SetFc"))
	r.GET("/gain/:port", ps.PortSpecificationAPI("SetGain"))
	vs := web.NewViews(*argReset)
	r.GET("/vlist", vs.List)
	r.GET("/gettuner/:port", vs.PortSpecificationAPI("GetTuner"))
	r.GET("/settuner/:port", vs.PortSpecificationAPI("SetPPM"))
	r.GET("/spectrum/:port", vs.PortSpecificationAPI("Spectrum"))
	r.GET("/vopen/:port", vs.NewView)
	r.GET("/fm/:port", func(c *gin.Context) {
		port := web.Str2int(c.Param("port"))
		v, ok := vs.GetView(port)
		if !ok {
			c.JSON(http.StatusOK, web.Response{"Cannot find", nil})
			return
		}
		var err error
		fmv, err = web.NewFMV(&v.FTView)
		if err != nil {
			c.JSON(http.StatusOK, web.Response{nil, err})
			return
		}
		go fmv.Start()
		c.JSON(http.StatusOK, web.Response{nil, nil})
	})
	r.GET("/fmstop", func(c *gin.Context) {
		if fmv != nil {
			fmv.Stop(c)
			// c.JSON(http.StatusOK, web.Response{"Stop FM", nil})
		} else {
			c.JSON(http.StatusOK, web.Response{"FM not Start", nil})
		}
	})

	r.GET("/afc", func(c *gin.Context) {
		if fmv != nil {
			fmv.AFC(c)
			// c.JSON(http.StatusOK, web.Response{"FM afc off", nil})
		} else {
			c.JSON(http.StatusOK, web.Response{"FM not Start", nil})
		}
	})
	r.Run(":8080")
}
